#include "stable.h"
#include "QkConfig.h"
#include "QkLayout.h"
#include "QkBaseView.h"
#include "QkTocView.h"
#include "QkComicView.h"
#include "QkBookView.h"
#include "QkStatusPane.h"
#include "QkToolBar.h"
#include "QkMainWindow.h"
#include "QkViewManager.h"

QkMainWindow *QkMainWindow::m_currentMainWindow = NULL;

QkMainWindow::QkMainWindow()
{
	m_currentMainWindow = this;

	m_containerWidget = new QWidget();
	setCentralWidget(m_containerWidget);

	QVBoxLayout *vLayout = new QVBoxLayout();
	m_containerWidget->setLayout(vLayout);

	m_statusPane = new QkStatusPane();
	vLayout->addWidget(m_statusPane);

	m_viewManager = new QkViewManager(this);
	m_viewManager->addView(new QkTocView(this));
	m_viewManager->addView(new QkComicView(this));
	m_viewManager->addView(new QkBookView(this));

	vLayout->addWidget(m_viewManager);

	m_toolBar = new QkToolBar();
	vLayout->addWidget(m_toolBar);

	vLayout->setMargin(0);
	vLayout->setSpacing(0);

	setMinimumSize(qkConfig.miniAppSize());
	setMaximumSize(qkConfig.maxAppSize());

	for(int i = 0; i < m_viewManager->count(); i++)
	{
		connect(m_viewManager->viewAt(i), SIGNAL(navigate(QkBaseView*, QString)), this, SLOT(on_navigate(QkBaseView*, QString)));
	}

	m_viewManager->setActiveView(m_viewManager->viewAt(0));
}

QkMainWindow::~QkMainWindow()
{
}

void QkMainWindow::keyReleaseEvent(QKeyEvent *event)
{
	if(event->key() != Qt::Key_Return)
	{
		QMainWindow::keyReleaseEvent(event);
		return;
	}

	int n = m_viewManager->currentIndex();
	n = (n + 1) % m_viewManager->count();
	m_viewManager->setActiveView(m_viewManager->viewAt(n));
}

void QkMainWindow::on_navigate(QkBaseView *senderView, const QString &url)
{
	QkBaseView *targetView = viewFromUrl(url);

	if(targetView != senderView)
	{
		m_viewManager->setActiveView(targetView);
	}
}

QkBaseView *QkMainWindow::viewFromUrl(const QString &url)
{
	if(url == "toc")
	{
		return m_viewManager->viewAt(0);
	}
	else if(url == "comic")
	{
		return m_viewManager->viewAt(1);
	}
	else if(url == "book")
	{
		return m_viewManager->viewAt(2);
	}

	Q_ASSERT(0);

	return NULL;
}

QkToolBar *QkMainWindow::toolBar() const
{
	return m_toolBar;
}

QkMainWindow *QkMainWindow::current()
{
	return m_currentMainWindow;
}